package com.wwl.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wwl
 * @version 1.0
 * @date 2021/8/9 20:30
 * @description:
 */
@Component
public class MyLB implements LoadBalancer{
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private final int getAndIncrement(){
        int current;
        int next;
        do{
            current= this.atomicInteger.get();
            next = current>= 2147483647 ? 0 : current + 1;
        }while (!this.atomicInteger.compareAndSet(current,next));//第一个参数期望值，第二个参数是修改值
        System.out.println("********第几次访问，次数next:"+next);
        return next;
    }

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstanceList) {
        int index = getAndIncrement()%serviceInstanceList.size();
        return serviceInstanceList.get(index);
    }
}
